package com.stetho.ai.a;

import android.util.Log;

import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;

/**
 * ai分析
 * create by duxl 2022/6/26
 */
public class AI {

    private final String TAG = "AI";
    private boolean isInit = false;

    private AI() {
        if (!Python.isStarted()) {
            long start = System.currentTimeMillis();
            Log.i(TAG, "start AI...");
            Python.start(new AndroidPlatform(App.instance));
            Log.i(TAG, "start AI耗时=" + (System.currentTimeMillis() - start));
        }
    }

    public static AI getInstance() {
        return SingleHolder.INSTANCE;
    }

    private static class SingleHolder {
        private static AI INSTANCE = new AI();
    }

    /**
     * AI初始化
     */
    public void init() {
        long start = System.currentTimeMillis();
        Log.i(TAG, "AI初始化...");
        if (!isInit) {
            Python py = Python.getInstance();
            py.getModule("init").callAttr("initModel");
            isInit = true;
        }
        Log.i(TAG, "AI初始化耗时=" + (System.currentTimeMillis() - start));
    }

    /**
     * pcm转wav
     *
     * @param pcmPath pcm音频的路径
     * @param wavPath 转成wav文件后的保存路径
     */
    public void pcmToWav(String pcmPath, String wavPath) {
        long start = System.currentTimeMillis();
        Log.i(TAG, "pcm文件转Wav文件, pcmPath=" + pcmPath);
        Log.i(TAG, "pcm文件转Wav文件, wavPath=" + wavPath);
        Python py = Python.getInstance();
        py.getModule("pcm_wav").callAttr("transfer", pcmPath, wavPath);
        Log.i(TAG, "pcm文件转Wav文件耗时=" + (System.currentTimeMillis() - start));
    }

    /**
     * 根据wav文件获得心音是否正常
     *
     * @param wavPath wav 文件
     * @return 返回是否正常
     */
    public String getResult(String wavPath) {
        long start = System.currentTimeMillis();
        Log.i(TAG, "根据wav文件获得心音是否正常, wavPath=" + wavPath);
        Python py = Python.getInstance();
        PyObject obj1 = py.getModule("get_result").callAttr("test", wavPath);
        String result = obj1.toJava(String.class);
        Log.i(TAG, "根据wav文件获得心音是否正常, result=" + result + ", 耗时=" + (System.currentTimeMillis() - start));
        return result;
    }
}
